package co.yixiang.yshop.module.crm.service.crmworkwxconfig;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import co.yixiang.yshop.module.crm.controller.admin.crmworkwxconfig.vo.*;
import co.yixiang.yshop.module.crm.dal.dataobject.crmworkwxconfig.CrmWorkWxConfigDO;
import co.yixiang.yshop.framework.common.pojo.PageResult;
import co.yixiang.yshop.framework.common.pojo.PageParam;
import co.yixiang.yshop.framework.common.util.object.BeanUtils;

import co.yixiang.yshop.module.crm.dal.mysql.crmworkwxconfig.CrmWorkWxConfigMapper;

import static co.yixiang.yshop.framework.common.exception.util.ServiceExceptionUtil.exception;
import static co.yixiang.yshop.module.crm.enums.ErrorCodeConstants.*;

/**
 * 企业微信配置 Service 实现类
 *
 * @author yshop
 */
@Service
@Validated
public class CrmWorkWxConfigServiceImpl implements CrmWorkWxConfigService {

    @Resource
    private CrmWorkWxConfigMapper workWxConfigMapper;

    @Override
    public Integer createWorkWxConfig(CrmWorkWxConfigSaveReqVO createReqVO) {
        // 插入
        CrmWorkWxConfigDO workWxConfig = BeanUtils.toBean(createReqVO, CrmWorkWxConfigDO.class);
        workWxConfigMapper.insert(workWxConfig);
        // 返回
        return workWxConfig.getId();
    }

    @Override
    public void updateWorkWxConfig(CrmWorkWxConfigSaveReqVO updateReqVO) {
        // 校验存在
        validateWorkWxConfigExists(updateReqVO.getId());
        // 更新
        CrmWorkWxConfigDO updateObj = BeanUtils.toBean(updateReqVO, CrmWorkWxConfigDO.class);
        workWxConfigMapper.updateById(updateObj);
    }

    @Override
    public void deleteWorkWxConfig(Integer id) {
        // 校验存在
        validateWorkWxConfigExists(id);
        // 删除
        workWxConfigMapper.deleteById(id);
    }

    private void validateWorkWxConfigExists(Integer id) {
        if (workWxConfigMapper.selectById(id) == null) {
            throw exception(WORK_WX_CONFIG_NOT_EXISTS);
        }
    }

    @Override
    public CrmWorkWxConfigDO getWorkWxConfig(Integer id) {
        return workWxConfigMapper.selectOne(new LambdaQueryWrapper<CrmWorkWxConfigDO>()
                .orderByDesc(CrmWorkWxConfigDO::getId).last("limit 1"));
    }

    @Override
    public PageResult<CrmWorkWxConfigDO> getWorkWxConfigPage(CrmWorkWxConfigPageReqVO pageReqVO) {
        return workWxConfigMapper.selectPage(pageReqVO);
    }

}